package net.colorlotus7;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Description: nio通信服务端处理器
 * @Author: Jason.zhu
 * @Create: 2020/02/19 11:27
 */

public class NioClientHandle implements Runnable {
    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;

    private volatile boolean started;

    public NioClientHandle(String ip, int port){
        this.host = ip;
        this.port = port;

        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);//是否阻塞
            started = true;
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void stop(){
        started = false;
    }

    @Override
    public void run() {
        try {
            doConnect();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (started){
            try{
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> it = keys.iterator();
                SelectionKey key = null;
                while (it.hasNext()){
                    key = it.next();
                    it.remove();
                    handleInput(key);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    private void handleInput(SelectionKey key)throws IOException{
        if(key.isValid()){
            SocketChannel sc = (SocketChannel)key.channel();
            if(key.isConnectable()){
                if(sc.finishConnect()){}
                else {
                    System.exit(1);
                }
            }

            if(key.isReadable()){//读取从服务端发送过来的消息
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(buffer);
                if(readBytes > 0){
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    String result = new String(bytes, "UTF-8");
                    System.out.println("accept message: " + result);
                }
            }
        }
    }

    //发送消息
    private void doWrite(SocketChannel channel, String request)throws IOException{
        //将消息转为字节码
        byte[] bytes = request.getBytes();
        //根据数组容量闯将ByteBuffer
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        //将字节数组复制到缓冲区
        writeBuffer.put(bytes);
        //flip操作
        writeBuffer.flip();
        //发送缓冲区的字节数组
        channel.write(writeBuffer);
    }

    //执行连接服务端
    private void doConnect()throws IOException{
        if(socketChannel.connect(new InetSocketAddress(host,port))){}
        else {
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
    }

    //发送消息给服务端
    public void sendMsg(String msg)throws Exception{
        socketChannel.register(selector, SelectionKey.OP_READ);
        doWrite(socketChannel, msg);
    }
}
